const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const Role = require('../models/Role');
const { generateVerificationCode, sendVerificationEmail } = require('../utils/emailService');
const { generateAccessToken, verifyAccessToken } = require('../utils/tokenService');

const errorRes = (res, message, code = 400) => res.status(code).json({ code, message });
const validateObjectId = id => mongoose.Types.ObjectId.isValid(id);
const findRole = async name => await Role.findOne({ name });

// 发送邮箱验证码
router.post('/send-code', async (req, res) => {
  try {
    const { email } = req.body;

    if (!email) return errorRes(res, '请提供邮箱地址');

    const code = generateVerificationCode();
    let user = await User.findOne({ email });

    if (user && user.isVerified) return errorRes(res, '该邮箱已被注册');

    const codeExpires = new Date(Date.now() + 10 * 60 * 1000);

    if (!user) {
      const defaultRole = await Role.findOne({ isDefault: true });
      if (!defaultRole) return errorRes(res, '系统错误：未找到默认角色', 500);
      user = await User.create({
        email,
        username: email.split('@')[0],
        password: code,
        verificationCode: code,
        codeExpires,
        isVerified: false,
        roles: [defaultRole._id]
      });
    } else {
      user.verificationCode = code;
      user.codeExpires = codeExpires;
      await user.save();
    }

    const emailResult = await sendVerificationEmail(email, code);
    if (!emailResult.success) return errorRes(res, '发送验证码失败，请稍后重试', 500);

    res.json({ code: 200, message: '验证码已发送至您的邮箱，请在10分钟内完成验证' });
  } catch (e) {
    errorRes(res, '服务器错误', 500);
  }
});

// 注册
router.post('/verify-register', async (req, res) => {
  try {
    const { email, code, username, password, merchantId } = req.body;

    if (!email || !code || !username || !password) return errorRes(res, '请提供所有必要信息');

    const user = await User.findOne({ email }).select('+verificationCode +codeExpires');
    if (!user) return errorRes(res, '未找到该用户，请先获取验证码', 404);
    if (user.codeExpires < Date.now()) return errorRes(res, '验证码已过期，请重新获取');
    if (user.verificationCode !== code) return errorRes(res, '验证码错误');
    if (await User.findOne({ username })) return errorRes(res, '该商户名称已被使用，请更换');

    const defaultRole = await Role.findOne({ isDefault: true });
    if (!defaultRole) return errorRes(res, '系统错误：未找到默认角色', 500);

    user.username = username;
    user.password = password;
    user.isVerified = true;
    user.verificationCode = undefined;
    user.codeExpires = undefined;
    user.roles = [defaultRole._id];
    if (merchantId) user.merchantId = merchantId;
    const accessToken = generateAccessToken(user._id);
    await user.save();
    const permissions = await user.getAllPermissions();

    res.status(201).json({
      code: 201,
      message: '注册成功',
      data: {
        _id: user._id,
        email: user.email,
        username: user.username,
        isVerified: user.isVerified,
        roles: [{ _id: defaultRole._id, name: defaultRole.name, description: defaultRole.description }],
        permissions,
        accessToken
      }
    });
  } catch (e) {
    console.error('注册接口错误：', e); // 新增，输出详细错误信息
    if (e.code === 11000) return errorRes(res, '注册信息冲突，请检查后重试');
    errorRes(res, '服务器错误', 500);
  }
});

// 登录
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    if (!email || !password) return errorRes(res, '请提供邮箱和密码');

    const user = await User.findOne({ email }).select('+password');
    if (!user) return errorRes(res, '邮箱或密码错误', 401);
    if (!user.isVerified) return errorRes(res, '账号未验证，请先完成邮箱验证', 401);
    if (!(await user.matchPassword(password))) return errorRes(res, '邮箱或密码错误', 401);

    const accessToken = generateAccessToken(user._id);
    const userWithRoles = await User.findById(user._id).populate('roles');
    const permissions = await userWithRoles.getAllPermissions();

    res.json({
      code: 200,
      message: '登录成功',
      data: {
        _id: user._id,
        email: user.email,
        username: user.username,
        isVerified: user.isVerified,
        roles: userWithRoles.roles.map(role => ({
          _id: role._id,
          name: role.name,
          description: role.description
        })),
        permissions,
        accessToken
      }
    });
  } catch (e) {
    errorRes(res, '服务器错误', 500);
  }
});

// 获取所有商户数据
router.get('/all-merchants', async (req, res) => {
  try {
    const { status, page = 1, limit = 10, search } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const Product = require('../models/Product');
    const merchantRole = await findRole('merchant');
    if (!merchantRole) return errorRes(res, '商户角色不存在', 404);
    const query = { roles: { $in: [merchantRole._id, merchantRole._id.toString()] } };
    if (status && status !== 'all') query.status = status;
    if (search) query.$or = [
      { username: { $regex: search, $options: 'i' } },
      { email: { $regex: search, $options: 'i' } },
      { merchantId: { $regex: search, $options: 'i' } }
    ];
    const total = await User.countDocuments(query);
    const merchants = await User.find(query).sort({ createdAt: -1 }).skip(skip).limit(parseInt(limit));
    const formattedMerchants = await Promise.all(merchants.map(async merchant => {
      const productCount = await Product.countDocuments({ userId: merchant._id });
      const products = await Product.find({ userId: merchant._id });
      const salesAmount = products.reduce((total, product) => total + (product.price * product.sales), 0);
      return {
        _id: merchant._id,
        email: merchant.email,
        username: merchant.username,
        merchantId: merchant.merchantId || `M${Math.floor(10000 + Math.random() * 90000)}`,
        status: merchant.status || '正常',
        productCount,
        salesAmount,
        registrationDate: merchant.registrationDate || merchant.createdAt,
        createdAt: merchant.createdAt,
        updatedAt: merchant.updatedAt
      };
    }));
    res.json({
      code: 200,
      message: '获取商户数据成功',
      data: formattedMerchants,
      pagination: {
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    errorRes(res, '获取商户数据失败', 500);
  }
});

// 获取当前用户信息
router.get('/me', async (req, res) => {
  try {
    let token;

    if (
      req.headers.authorization &&
      req.headers.authorization.startsWith('Bearer')
    ) {
      token = req.headers.authorization.split(' ')[1];
      const decoded = verifyAccessToken(token);

      if (decoded) {
        const user = await User.findById(decoded.id).populate('roles');
        if (user) {
          const permissions = await user.getAllPermissions();
          return res.json({
            code: 200,
            data: {
              _id: user._id,
              email: user.email,
              username: user.username,
              isVerified: user.isVerified,
              roles: user.roles.map(role => ({
                _id: role._id,
                name: role.name,
                description: role.description
              })),
              permissions
            }
          });
        }
      }
    }

    return errorRes(res, '未授权', 401);
  } catch (e) {
    errorRes(res, '服务器错误', 500);
  }
});

// 退出登录
router.post('/logout', (req, res) =>
  res.json({ code: 200, message: '退出登录成功' })
);

// 获取商户详情
router.get('/merchant/:id', async (req, res) => {
  try {
    const merchantId = req.params.id;
    if (!validateObjectId(merchantId)) return errorRes(res, '无效的商户ID');
    const merchant = await User.findById(merchantId);
    if (!merchant) return errorRes(res, '商户不存在', 404);
    const Product = require('../models/Product');
    const productCount = await Product.countDocuments({ userId: merchant._id });
    const products = await Product.find({ userId: merchant._id }).sort({ createdAt: -1 });
    const salesAmount = products.reduce((total, product) => total + (product.price * product.sales), 0);
    const recentProducts = products.slice(0, 5);
    res.json({
      code: 200,
      message: '获取商户详情成功',
      data: {
        _id: merchant._id,
        email: merchant.email,
        username: merchant.username,
        merchantId: merchant.merchantId || `M${Math.floor(10000 + Math.random() * 90000)}`,
        status: merchant.status || '正常',
        productCount,
        salesAmount,
        registrationDate: merchant.registrationDate || merchant.createdAt,
        createdAt: merchant.createdAt,
        updatedAt: merchant.updatedAt,
        recentProducts: recentProducts.map(product => ({
          _id: product._id,
          name: product.name,
          price: product.price,
          image: product.image,
          sales: product.sales
        }))
      }
    });
  } catch (e) {
    errorRes(res, '获取商户详情失败', 500);
  }
});

// 冻结商户
router.post('/merchant/freeze/:id', async (req, res) => {
  try {
    const merchantId = req.params.id;
    if (!validateObjectId(merchantId)) return errorRes(res, '无效的商户ID');
    const merchant = await User.findByIdAndUpdate(merchantId, { status: '已冻结' }, { new: true });
    if (!merchant) return errorRes(res, '商户不存在', 404);
    const io = req.app.get('io');
    if (io && merchantId)
      io.to(merchantId).emit('userStatusChanged', {
        userId: merchantId,
        status: '已冻结',
        message: '您的账号已被冻结，请联系管理员。'
      });
    res.json({
      code: 200,
      message: '商户已冻结',
      data: { _id: merchant._id, username: merchant.username, status: merchant.status }
    });
  } catch (e) {
    errorRes(res, '冻结商户失败', 500);
  }
});

// 解冻商户
router.post('/merchant/unfreeze/:id', async (req, res) => {
  try {
    const merchantId = req.params.id;
    if (!validateObjectId(merchantId)) return errorRes(res, '无效的商户ID');
    const merchant = await User.findByIdAndUpdate(merchantId, { status: '正常' }, { new: true });
    if (!merchant) return errorRes(res, '商户不存在', 404);
    const io = req.app.get('io');
    if (io && merchantId)
      io.to(merchantId).emit('userStatusChanged', {
        userId: merchantId,
        status: '正常',
        message: '您的账号已恢复正常。'
      });
    res.json({
      code: 200,
      message: '商户已解冻',
      data: { _id: merchant._id, username: merchant.username, status: merchant.status }
    });
  } catch (e) {
    errorRes(res, '解冻商户失败', 500);
  }
});

// 审核商户
router.post('/merchant/approve/:id', async (req, res) => {
  try {
    const merchantId = req.params.id;
    if (!validateObjectId(merchantId)) return errorRes(res, '无效的商户ID');
    const merchant = await User.findById(merchantId);
    if (!merchant) return errorRes(res, '商户不存在', 404);
    if (merchant.status !== '待审核') return errorRes(res, '只有待审核状态的商户才能进行审核操作');
    merchant.status = '正常';
    await merchant.save();
    const io = req.app.get('io');
    if (io && merchantId)
      io.to(merchantId).emit('userStatusChanged', {
        userId: merchantId,
        status: '正常',
        message: '您的账号已审核通过，可以正常使用。'
      });
    res.json({
      code: 200,
      message: '商户审核通过',
      data: { _id: merchant._id, username: merchant.username, status: merchant.status }
    });
  } catch (e) {
    errorRes(res, '审核商户失败', 500);
  }
});

// 获取平台用户总数
router.get('/total-users', async (req, res) => {
  try {
    const adminRole = await findRole('admin');
    if (!adminRole) return errorRes(res, '获取角色信息失败', 500);
    const data = await User.countDocuments({ isVerified: true, roles: { $nin: [adminRole._id] } });
    res.json({ code: 200, data, message: '获取平台用户总数成功' });
  } catch (e) {
    errorRes(res, '获取平台用户总数失败', 500);
  }
});

// 获取商户总数
router.get('/total-merchants', async (req, res) => {
  try {
    const merchantRole = await findRole('merchant');
    if (!merchantRole) return errorRes(res, '获取角色信息失败', 500);
    const data = await User.countDocuments({ roles: { $in: [merchantRole._id] }, isVerified: true });
    res.json({ code: 200, data, message: '获取商户总数成功' });
  } catch (e) {
    errorRes(res, '获取商户总数失败', 500);
  }
});

module.exports = router; 